﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using GameLib;
using System.Windows.Input;
using GameLib.WorldMap;
using Sandbox.Editor.Modes.ModePanels;
using System.Windows;
using GameLib.Utils;

namespace Sandbox.Editor.Modes
{
	public class TerrainMode : EditorMode
	{
		public TerrainMode(EditorWindow window)
			: base(window)
		{
			Window.TerrainPanel.Mode = this;
		}

		public override void MapWindow_MouseLeftButtonDown(MouseButtonEventArgs e)
		{
			base.MapWindow_MouseLeftButtonDown(e);

			m_IsPaitingTerrain = true;

			if (MouseOverTile != null)
			{
				PaintAt(MouseOverTile.X, MouseOverTile.Y);
			}
		}

		public override void MapWindow_MouseLeftButtonUp(MouseButtonEventArgs e)
		{
			base.MapWindow_MouseLeftButtonUp(e);

			m_IsPaitingTerrain = false;

		}

		public override void MapWindow_LoseFocus(MouseEventArgs e)
		{
			base.MapWindow_LoseFocus(e);
			m_IsPaitingTerrain = false;
		}

		public void OnBrushSizeChanged(RoutedPropertyChangedEventArgs<double> e)
		{
			MapScene.CursorSize = BrushSize;
		}

		protected override void OnEnterTile(Tile tile)
		{
			base.OnEnterTile(tile);

			if (m_IsPaitingTerrain)
			{
				PaintAt(tile.X, tile.Y);
			}
		}

		private void PaintAt(int x, int y)
		{
			GameVector[] tileCoords;
			Map.RasterizeCircle(new GameVector(x, y), BrushSize, out tileCoords);

			foreach (GameVector coord in tileCoords)
			{
				Tile tile = MapScene.Map.GetTile((int)coord.X, (int)coord.Y);
				if (tile != null)
					PaintTile(tile);
			}					
		}

		private void PaintTile(Tile tile)
		{
			if (tile == null)
				return;

			ListBoxItem selItem = Panel.ListBoxTerrain.SelectedItem as ListBoxItem;

			if (selItem != null)
			{
				tile.Terrain = selItem.Content as Terrain;
			}
		}

		private TerrainPanel Panel
		{
			get { return Window.TerrainPanel; }
		}

		private int BrushSize
		{
			get { return (int)Panel.SliderBrushSize.Value; }
		}

		private bool m_IsPaitingTerrain;

	}
}
